package ch.ethz.eai.facade;

import java.rmi.RemoteException;

import net.webservicex.www.GlobalWeatherStub;
import net.webservicex.www.GlobalWeatherStub.GetWeather;
import net.webservicex.www.GlobalWeatherStub.GetWeatherResponse;

import org.apache.axis2.AxisFault;

import ch.ethz.eai.data.Location;
import ch.ethz.eai.data.WeatherStatus;

public class WeatherFacade {
	
	/**
	 * Get the weather for a location defined as town and counrty name.
	 * @param where
	 * @return
	 */
	public static WeatherStatus getWeatherFor(Location where) {
		try {
			GlobalWeatherStub stub = new GlobalWeatherStub();
			GetWeather req = new GetWeather();
			req.setCityName(where.getTown());
			req.setCountryName(where.getCountry());
			GetWeatherResponse result = stub.getWeather(req);
			WeatherStatus w = createInstanceFromDescription(result.getGetWeatherResult(), where);
			if (w.getStatus()!=WeatherStatus.STAT_UNKNOWN) {
				return w;
			} else {
				return null;
			}
		} catch (AxisFault e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		
		}
		
		return null;
	}
	
	/**
	 * Will try to parse in whatever description to find the weather type.
	 * Upon failure it returns a weather with TYPE_UNKNOWN.
	 * @param how
	 * @param where
	 * @return
	 */
	private static WeatherStatus createInstanceFromDescription(String how, Location where) {
		int status = WeatherStatus.STAT_CLEAR;
		String descr = how.toLowerCase();
		
		//DISCLAIMER:
		//	we should use this only to extract data from the web service
		
		if (descr.contains("clear")) {
			status = WeatherStatus.STAT_CLEAR;
		} else if (descr.contains("overcast")) {
			status = WeatherStatus.STAT_CLOUDS;
		} else if (descr.contains("rain")) {
			status = WeatherStatus.STAT_RAIN;
		} else if (descr.contains("snow")) {
			status = WeatherStatus.STAT_SNOW;
		} else if (descr.contains("storm")) {
			status = WeatherStatus.STAT_STORM;
		} 
		
		return new WeatherStatus(status, where);
		
	}
}
